/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.apache.dolphinscheduler.server.master.utils;

import org.apache.dolphinscheduler.common.IStoppable;
import org.apache.dolphinscheduler.common.constants.Constants;
import org.apache.dolphinscheduler.common.lifecycle.ServerLifeCycleManager;
import org.apache.dolphinscheduler.common.thread.ThreadUtils;
import org.apache.dolphinscheduler.scheduler.api.SchedulerApi;
import org.apache.dolphinscheduler.server.master.registry.MasterRegistryClient;
import org.apache.dolphinscheduler.server.master.rpc.MasterRPCServer;
import org.apache.dolphinscheduler.server.master.runner.EventExecuteService;
import org.apache.dolphinscheduler.server.master.runner.FailoverExecuteThread;
import org.apache.dolphinscheduler.server.master.runner.MasterSchedulerBootstrap;
import org.apache.dolphinscheduler.server.master.runner.task.TaskProcessorFactory;
import org.apache.dolphinscheduler.service.bean.SpringApplicationContext;
import org.apache.dolphinscheduler.service.task.TaskPluginManager;
import org.quartz.SchedulerException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.annotation.PostConstruct;

@SpringBootApplication
@ComponentScan("org.apache.dolphinscheduler")
@EnableTransactionManagement
@EnableCaching
public class MasterServer implements IStoppable {

  private static final Logger logger = LoggerFactory.getLogger(MasterServer.class);

  @Autowired
  private SpringApplicationContext springApplicationContext;

  /**
   * zk集群节点、节点资源信息管理
   */
  @Autowired
  private MasterRegistryClient masterRegistryClient;

  /**
   * SPILoader
   */
  @Autowired
  private TaskPluginManager taskPluginManager;

  /**
   * 这里就是一个任务调度派发的线程，TaskInstance派发后，最终的执行响应就得看事件回调了
   * 所以后续应该仔细看Processor、StateEventHandler、TaskEventHandler处理机制，比如任务是否执行完毕、成功、失败，流程是否完毕、成功失败或者重试等等......
   */
  @Autowired
  private MasterSchedulerBootstrap masterSchedulerBootstrap;

  /**
   * QuartzSchedulerThread
   */
  @Autowired
  private SchedulerApi schedulerApi;

  /**
   * WorkflowExecuteThreadPool循环执行workflowEventHandler();
   * 获取stateEvents中的状态事件StateEvent，交由对应的状态Handler处理
   * 这个状态事件，是由StateEventResponseService.addStateChangeEvent放入的
   */
  @Autowired
  private EventExecuteService eventExecuteService;

  /**
   * 故障检测，实例运行、待停止、待...这种，检测host是否存在
   * 不存在则failover task、processInstance，新插入命令 更新流程和任务状态
   */
  @Autowired
  private FailoverExecuteThread failoverExecuteThread;

  /**
   * nettyServer、nettyClient、Processor
   * 这里核心处理，TaskStateEventHandler、WorkflowStateEventHandler
   */
  @Autowired
  private MasterRPCServer masterRPCServer;

  public static void main(String[] args) {
    Thread.currentThread().setName(Constants.THREAD_NAME_MASTER_SERVER);
    SpringApplication.run(MasterServer.class);
  }

  /**
   * run master server
   */
  @PostConstruct
  public void run() throws SchedulerException {
    // NettyServer、NettyClient，通过Processor解耦
    // ConcurrentHashMap<CommandType, Pair<Processor, ThreadPool>>
    this.masterRPCServer.start();

    // SPI机制，TaskChannel操作任务
    this.taskPluginManager.loadPlugin();

    // ZK节点注册中心，目录树操作，强一致性原则
    this.masterRegistryClient.start();
    this.masterRegistryClient.setRegistryStoppable(this);

    // 主节点工作流调度核心API
    this.masterSchedulerBootstrap.init();
    this.masterSchedulerBootstrap.start();

    this.eventExecuteService.start();
    this.failoverExecuteThread.start();

    // QuartzSchedulerThread，Quartz Store、Trigger、ThreadPool
    this.schedulerApi.start();

    Runtime.getRuntime().addShutdownHook(new Thread(() -> {
      if (!ServerLifeCycleManager.isStopped()) {
        close("MasterServer shutdownHook");
      }
    }));
  }

  /**
   * gracefully close
   *
   * @param cause close cause
   */
  public void close(String cause) {
    // set stop signal is true
    // execute only once
    if (!ServerLifeCycleManager.toStopped()) {
      logger.warn("MasterServer is already stopped, current cause: {}", cause);
      return;
    }
    // thread sleep 3 seconds for thread quietly stop
    ThreadUtils.sleep(Constants.SERVER_CLOSE_WAIT_TIME.toMillis());
    try (
        SchedulerApi closedSchedulerApi = schedulerApi;
        MasterSchedulerBootstrap closedSchedulerBootstrap = masterSchedulerBootstrap;
        MasterRPCServer closedRpcServer = masterRPCServer;
        MasterRegistryClient closedMasterRegistryClient = masterRegistryClient;
        // close spring Context and will invoke method with @PreDestroy annotation to destroy beans.
        // like ServerNodeManager,HostManager,TaskResponseService,CuratorZookeeperClient,etc
        SpringApplicationContext closedSpringContext = springApplicationContext) {

      logger.info("Master server is stopping, current cause : {}", cause);
    } catch (Exception e) {
      logger.error("MasterServer stop failed, current cause: {}", cause, e);
      return;
    }
    logger.info("MasterServer stopped, current cause: {}", cause);
  }

  @Override
  public void stop(String cause) {
    close(cause);
  }
}
